package v1

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
)

const imageName = 1024 * 1024 * 2

var Upload string

func File(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "获取图片失败！",
		})
	}
	open, err := file.Open()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "打开图片失败！",
		})
	}
	//先判断上传文件的大小
	if file.Size > imageName {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "图片过大！",
		})
	}
	status := 0
	//判断上传文件的后缀
	suffix := strings.Split(file.Filename, ".")
	typeImage := []string{"webp", "jpg", "png"}
	for _, val := range typeImage {
		if suffix[len(suffix)-1] == val {
			status = 1
		}
	}
	if status != 1 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "获取图片失败！",
		})
	}
	//设置文件路径
	times := time.Now().UnixNano()
	uploadName := strconv.Itoa(int(times)) + "." + suffix[len(suffix)-1]
	upload := "../server/img/" + strconv.Itoa(int(times)) + "." + suffix[len(suffix)-1]
	files, err := os.Create(upload)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "上传图片失败！",
		})
	}
	_, err = io.Copy(files, open)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "copy图片失败！",
		})
	}
	// 创建OSSClient实例。
	// yourEndpoint填写Bucket对应的Endpoint，以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
	client, err := oss.New("https://oss-cn-beijing.aliyuncs.com", "LTAI5tAPUemGc8JLt3KAUiD3", "rqZMyxSl0IlMIHkq2lsoE7pCTix4El")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	// 填写存储空间名称，例如examplebucket。
	bucket, err := client.Bucket("sx13")
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	opens, err := file.Open()
	if err != nil {
	}
	all, err := io.ReadAll(opens)
	if err != nil {
	}
	// 依次填写Object的完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径（例如D:\\localpath\\examplefile.txt）。
	err = bucket.PutObject(uploadName, bytes.NewBuffer(all))
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	Upload = "https://sx13.oss-cn-beijing.aliyuncs.com/" + uploadName
	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"msg":    "上传阿里云成功！",
		"upload": Upload,
	})
}
